package com.coderman.domainservice.blogtopic.app.executor;

import com.alibaba.fastjson.JSON;
import com.coderman.domainservice.blogtopic.app.command.PublishBlogCommentCmd;
import com.coderman.domainservice.blogtopic.client.dto.BlogCommentDTO;
import com.coderman.domainservice.blogtopic.domain.ability.BlogIndiceService;
import com.coderman.domainservice.blogtopic.domain.convertor.BlogCommentConvertor;
import com.coderman.domainservice.blogtopic.domain.gataway.BlogRepository;
import com.coderman.domainservice.blogtopic.domain.model.event.provider.PublishBlogCommentEvent;
import com.coderman.domainservice.blogtopic.infrast.dubbo.BlogCheckAdapterService;
import com.coderman.domainservice.blogtopic.infrast.mq.Constants;
import com.coderman.domainservice.blogtopic.infrast.mq.provider.MqSendService;
import com.coderman.domainservice.member.domain.model.user.valueobject.IndiceEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Description:
 * date: 2021/3/31
 *
 * @author shenshuai
 * @version 1.0.0
 * @since JDK 1.8
 */
@Service
public class PublishBlogCommentCmdExe {
    @Autowired
    private BlogCheckAdapterService blogCheckAdapterService;

    @Autowired
    private BlogRepository blogRepository;

    @Autowired
    private BlogIndiceService blogIndiceService;

    @Autowired
    private MqSendService mqSendService;

    /**
     * 发布博客命令执行入口
     * @param cmd
     * @return
     * 注意这里有事务操作
     */
    //@Transactional
    public String execute(PublishBlogCommentCmd cmd) {
        //1.数据校验
        check(cmd.getBlogCommentDTO());

        //3.调用评论内容审核接口
        String result = blogCheckAdapterService.checkComment(cmd.getBlogCommentDTO());
        if(result.equals("success")){
            //2.调用gataway接口
            blogRepository.publishComment(BlogCommentConvertor.INSTANCE.dto2bo(cmd.getBlogCommentDTO()));
            //3.评论发布-->发消息
              //3.1 更新基于博客维度的评论数
                //由于本身属于博客/帖子领域,可以采用发内部事件或者直接调用数据统计服务更新博客评论数
                //这里直接调用数据统计服务，二者优缺点可以自己琢磨下
            blogIndiceService.updateCount(cmd.getBlogCommentDTO().getBlogId(), IndiceEnum.COMMENT_COUNT.getCode(), true);

              //3.2 更新基于用户维度的评论消息，这里通过消息mq发远程事件
            PublishBlogCommentEvent publishBlogCommentEvent = new PublishBlogCommentEvent();
            publishBlogCommentEvent.setUserId(cmd.getBlogCommentDTO().getUserid());
            publishBlogCommentEvent.setPublishType(2);
            mqSendService.send(Constants.TOPIC_CENTER, JSON.toJSONString(publishBlogCommentEvent));
        }else {
            //4.给用户发送通知
        }

        return "success";
    }
    private String check(BlogCommentDTO blogCommentDTO){
        return "success";
    }
}
